package com.shuaiche.yeguan.net.http;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.google.gson.Gson;
import com.shuaiche.yeguan.ui.login.SCLoginWrapHelper;
import com.shuaiche.yeguan.model.BaseResponseModel;

import org.apache.http.conn.ConnectTimeoutException;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import okhttp3.Headers;

/**
 * 网络请求回调实现类
 */
public abstract class HttpCallBack<T> implements CallBack {

    public static final String NET_ERROR = "404";
    private Context mContext;
    Handler mHandler;
    private Class<?> cls;
    private Gson gson;

    public HttpCallBack(final Context context) {
        mContext = context.getApplicationContext();
        mHandler = new Handler(Looper.getMainLooper());
    }


    @Override
    public void onStart() {

    }

    @Override
    public void onFinish() {

    }

    @Override
    public void onSuccess(String result) {
        try {

            gson = new Gson();
            cls = clazzInfo(this);
            final T objResult = (T) gson.fromJson(result,cls);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        BaseResponseModel baseBean = (BaseResponseModel) objResult;
                        if ("0".equals(baseBean.getCode())){
                            onSuccessed(objResult);
                        }else {
                            if ("-113".equals(baseBean.getCode())){//登录失效
                                SCLoginWrapHelper.starLogintActivity(mContext);
                            }else {
                                onFailured(baseBean.getCode(), baseBean.getMsg());
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
            });

        }catch (Exception e){
            Toast.makeText(mContext,"数据解析失败",Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onSuccess(String result, Headers headers) {
        try {
            gson = new Gson();
            cls = clazzInfo(this);
            final T objResult = (T) gson.fromJson(result,cls);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    onSuccessed(objResult);
                }
            });

        }catch (Exception e){
            Toast.makeText(mContext,"数据解析失败",Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onFailure(final Exception e) {
        if (e != null){
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    String error = "请求异常";

                    if (e instanceof ConnectException) {// 不能在指定的ip和端口上建立连接
                        error = "无法和服务器建立连接";
                    } else if (e instanceof ConnectTimeoutException) {// 建立连接超时
                        error = "与服务器建立连接超时";
                    } else if (e instanceof SocketTimeoutException) {// 读取数据超时
                        error = "服务器读取数据超时";
                    } else if (e instanceof UnknownHostException) {
                        error = "网络异常";
                    } else if( e instanceof InterruptedIOException){
                        error = "网络连接失败";
                    }
                    else if(e instanceof IOException){
                        if(e.getLocalizedMessage().equals("Canceled")){
                            return;
                        }
                        error = "网络连接中断";
                    }
                    Toast.makeText(mContext,error,Toast.LENGTH_SHORT).show();
                    onFailured(NET_ERROR,"网络错误");
                }
            });
        }else {
            mHandler.post(new Runnable(){
                @Override
                public void run() {
                    onFailured(NET_ERROR,"网络错误");
                }
            });

        }
    }

    public abstract void onSuccessed(T result);

    public abstract void onFailured(String errorCode,String errMsg);

    public static <T>Class<?> clazzInfo(Object obj){
        Type genType = obj.getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        return (Class<?>) params[0];

    }
}
